<template>
  <div class="table-box" v-loading="loading.value">
    <div class="top-buttons">
      <el-button type="primary" @click="loadData">搜索</el-button>
      <el-button type="primary" @click="onAddClick">新增</el-button>
    </div>
    <AgGrid
      ref="agGridRef"
      :columns="columns"
      v-model="list"
      @handle="onHandle"
    />
    <div class="bottom-buttons">
      <el-button type="success" @click="onSaveClick">保存</el-button>
      <el-button v-if="false" type="info">历史记录</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

import AgGrid from "@/components/ag-grid/index.vue";

import AgColumn from "@/bean/vo/AgColumn";
import TypeVO from "@/bean/vo/TypeVO";
import TypeApi from "@/api/setting/type";
import Loading from "@/utils/Loading";

const $router = useRouter();

const agGridRef = ref<InstanceType<typeof AgGrid>>();

const columns = ref<AgColumn<TypeVO>[]>([
  {title: '名称', field: 'name', type: 'text', editable: true},
  {title: '显示名称', field: 'displayName', type: 'text', editable: true},
  {title: '操作', type: 'buttons', buttons: [
    {title: '管理字段', type: 'primary', size: 'small', eventType: 'manageField'},
    {title: '删除', type: 'danger', size: 'small', eventType: 'delete'},
  ]},
]);

const loading = reactive(new Loading());

const list = ref<Partial<TypeVO>[]>([]);

function onHandle(eventType: string, data: TypeVO) {
  if (eventType === 'delete') {
    onDeleteClick(data);
  }
  else if (eventType === 'manageField') {
    onManageFieldClick(data);
  }
}

function loadData() {
  return loading.execute(async() => {
    list.value = await TypeApi.getList();
    agGridRef.value.clear();
  });
}

function onAddClick() {
  agGridRef.value.add();
}

function onSaveClick() {
  return loading.execute(async() => {
    await TypeApi.save(agGridRef.value.getSubmitRows());
    ElMessage.success('保存成功');
    await loadData();
  });
}

function onDeleteClick(data: TypeVO) {
  agGridRef.value.remove(data);
}

function onManageFieldClick(data: TypeVO) {
  $router.push({
    path: '/setting/field',
    query: {
      typeId: data.id
    }
  });
}

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.table-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.top-buttons {
  margin-bottom: 10px;
  text-align: right
}
.bottom-buttons {
  margin-top: 10px;
}
</style>
